package com.ninong.ker.common.annotation.perm.aspect;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import com.ninong.ker.common.annotation.perm.CmdAdmin;
import com.ninong.ker.common.auth.SecurityAdmin;
import com.ninong.ker.common.exception.CmdException;

/**
 * 权限校验处理
 * @author cmd
 *
 */
@Aspect
@Component
public class CmdAdminAspect {
	
	@Autowired
	private SecurityAdmin securityAdmin;

	@Autowired
	private HttpServletRequest request;

	@Around("@annotation(com.ninong.ker.common.annotation.perm.CmdAdmin)")
	public Object around(ProceedingJoinPoint point) throws Throwable {
		Object proceed = null;
		MethodSignature ms = (MethodSignature) point.getSignature();
		Method method = ms.getMethod();
		CmdAdmin torchPerm = method.getAnnotation(CmdAdmin.class);
		if (torchPerm == null) {
			return point.proceed();
		}
		String token = securityAdmin.getToken(request);
		String[] value = torchPerm.value();
		List<String> list = Arrays.asList(value);
		if (StringUtils.isEmpty(value)) {
			proceed = point.proceed();
			return proceed;
		} else {
			List<String> authorities = securityAdmin.getAuthorities(token);
			List<String> intersection = authorities.stream().filter(item -> list.contains(item))
					.collect(Collectors.toList());
			if (!ObjectUtils.isEmpty(intersection) && intersection.size() > 0) {
				return point.proceed();
			} else {
				throw new CmdException("当前用户无权限");
			}
		}
	}

}
